<template>
  <div
    :class="{ 'l-rblock': !['full', 'btn'].includes(wraperType) }"
    style="overflow: hidden auto"
    v-loading.fullscreen="pageLoading"
    :element-loading-text="$t(pageLoadingText)"
  >
    <l-fullscreen-dialog
      :title="`${title}`"
      :visible.sync="midVisible"
      :showOk="false"
      @closed="handleClosed"
      @opened="handleOpened"
      ref="formDialog"
      v-if="wraperType == 'full'"
    >
      <template
        #headerRight
        v-if="(isRead && task && task.f_State == 1) || isChildProcess || currentNode.formWrodPrintCode"
      >
        <el-button
          v-if="isRead && task && task.f_State == 1"
          size="mini"
          type="primary"
          @click="handleRead"
          >{{ $t("确认阅读") }}</el-button
        >
        <el-button
          v-if="isChildProcess"
          size="mini"
          type="primary"
          @click="handleOpenParent"
          >{{ $t("父级流程") }}</el-button
        >

        <l-wordprint-btn
          style="margin-right: 8px"
          v-if="currentNode.formWrodPrintCode"
          :code="currentNode.formWrodPrintCode"
          :getFormData="getPrintData"
        ></l-wordprint-btn>
      </template>

      <l-layout class="l-tab-page" :right="400">
        <l-panel :style="{ 'padding-right': isRead ? '' : 0 }">
          <div class="l-auto-window" style="padding: 0 8px">
            <el-tabs v-model="activeName" @tab-click="handleTabClick">
              <el-tab-pane v-if="hasWfForm" :label="$t('表单信息')" name="form">
                <div class="l-rblock" v-loading="formSchemeLoding">
                  <template v-if="showForm">
                    <l-form-viewer
                      v-if="formType == '1'"
                      :formInfo="formInfo"
                      :isWfForm="true"
                      :authFieldsMap="formAuthFieldsMap"
                      ref="wfForm"
                    ></l-form-viewer>
                    <component
                      ref="wfForm"
                      v-else
                      :requiredMap="formRequiredMap"
                      :authFieldsMap="formAuthFieldsMap"
                      :isWfForm="true"
                      :is="sysFormComponent"
                      :isReadOnly="isWfReadOnly"
                    ></component>
                  </template>
                </div>
              </el-tab-pane>
              <el-tab-pane :label="$t('流程信息')" name="wfinfo">
                <l-layout style="background: #f1f2f5" :right="320">
                  <l-panel
                    class="flow-panel"
                    style="padding: 0; padding-top: 0"
                  >
                    <template #title>
                      <el-button-group>
                        <el-tooltip
                          effect="dark"
                          :content="$t('复原')"
                          placement="bottom"
                        >
                          <el-button
                            size="mini"
                            icon="el-icon-aim"
                            @click="resetZoom"
                          ></el-button>
                        </el-tooltip>
                        <el-tooltip
                          effect="dark"
                          :content="$t('放大')"
                          placement="bottom"
                        >
                          <el-button
                            size="mini"
                            icon="el-icon-zoom-in"
                            @click="handlerZoom(0.1)"
                          ></el-button>
                        </el-tooltip>
                        <el-tooltip
                          effect="dark"
                          :content="$t('缩小')"
                          placement="bottom"
                        >
                          <el-button
                            size="mini"
                            icon="el-icon-zoom-out"
                            @click="handlerZoom(-0.1)"
                          ></el-button>
                        </el-tooltip>
                      </el-button-group>

                      <div style="float: right">
                        <el-tag
                          size="small"
                          effect="plain"
                          style="margin-right: 8px"
                          >{{$t('正在审核')}}</el-tag
                        >
                        <el-tag
                          size="small"
                          effect="plain"
                          style="margin-right: 8px"
                          type="success"
                          >{{$t('已审核')}}</el-tag
                        >
                        <el-tag
                          size="small"
                          effect="plain"
                          style="margin-right: 8px"
                          type="danger"
                          >{{$t('已审核（驳回）')}}</el-tag
                        >
                      </div>
                    </template>
                    <b-wflow-viewer
                      ref="bflow"
                      isSimple
                      @elementClick="elementClick"
                    >
                    </b-wflow-viewer>
                  </l-panel>
                  <template #right>
                    <l-panel
                      v-if="nodeLogs.length > 0"
                      class="flow-panel"
                      style="padding: 0; padding-top: 0"
                    >
                      <template #title>{{ $t('记录信息') }}</template>
                      <div
                        class="l-rblock"
                        style="padding: 8px; overflow: hidden auto"
                      >
                        <el-timeline>
                          <el-timeline-item
                            :type="item.type"
                            v-for="(item, index) in nodeLogs"
                            :key="index"
                            :timestamp="item.time"
                            placement="top"
                          >
                            <el-card shadow="hover">
                              <div class="title">{{ item.name }}</div>
                              <div class="content">
                                <template v-if="item.taskType != 3">
                                  <l-user
                                    v-for="(userId, index2) in item.userIds"
                                    :key="index2"
                                    :value="userId"
                                  ></l-user>
                                  {{ item.des }}
                                </template>
                                <template v-else>
                                  <el-button
                                    size="mini"
                                    @click="OpenChildWf(item)"
                                    type="text"
                                    >{{ $t("查看") }}</el-button
                                  >
                                  <template v-if="item.isShowUser">
                                    <l-user
                                      v-for="(userId, index2) in item.userIds"
                                      :key="index2"
                                      :value="userId"
                                    ></l-user>
                                  </template>

                                  {{ item.des }}
                                </template>
                              </div>
                            </el-card>
                          </el-timeline-item>
                        </el-timeline>
                      </div>
                    </l-panel>
                  </template>
                </l-layout>
              </el-tab-pane>
              <el-tab-pane
                v-if="logs.length > 0"
                :label="$t('流转记录')"
                name="wflogs"
              >
                <div
                  class="l-rblock"
                  style="padding: 8px; overflow: hidden auto"
                >
                  <el-timeline>
                    <el-timeline-item
                      :type="item.type"
                      v-for="(item, index) in logs"
                      :key="index"
                      :timestamp="item.time"
                      placement="top"
                    >
                      <el-card shadow="hover">
                        <div class="title">{{ item.name }}</div>
                        <div class="content">
                          <template v-if="item.taskType != 3">
                            <l-user
                              v-for="(userId, index2) in item.userIds"
                              :key="index2"
                              :value="userId"
                            ></l-user>
                            {{ item.des }}
                          </template>
                          <template v-else>
                            <el-button
                              size="mini"
                              @click="OpenChildWf(item)"
                              type="text"
                              >{{ $t("查看") }}</el-button
                            >
                            <template v-if="item.isShowUser">
                              <l-user
                                v-for="(userId, index2) in item.userIds"
                                :key="index2"
                                :value="userId"
                              ></l-user>
                            </template>

                            {{ item.des }}
                          </template>
                        </div>
                      </el-card>
                    </el-timeline-item>
                  </el-timeline>
                </div>
              </el-tab-pane>
            </el-tabs>
          </div>
        </l-panel>

        <template #right v-if="!isRead">
          <l-panel style="padding-left: 0" :title="$t('审批栏')">
            <div class="l-rblock" style="padding: 8px">
              <el-form
                :model="formData"
                :rules="myRules"
                size="mini"
                ref="form"
              >
                <el-form-item
                  v-if="
                    !isCreateSub && (type != 'auditAndlook' || task != null)
                  "
                  :label="isCreateAgain ? $t('备注') : $t('审批意见')"
                  prop="des"
                >
                  <el-input
                    type="textarea"
                    v-model="formData.des"
                    :placeholder="$t('please enter')"
                    rows="3"
                  >
                  </el-input>
                </el-form-item>
                <el-form-item
                  :label="$t('流程标题')"
                  prop="title"
                  v-if="isCreateSub && isCustmerTitle"
                >
                  <el-input v-model="formData.title" :placeholder="$t('please enter')">
                  </el-input>
                </el-form-item>

                <el-form-item
                  prop="fileId"
                  v-if="isUploadFile"
                  style="margin-bottom:0;"
                >
                  <l-upload
                    v-model="formData.fileId"
                    showFileList="uploadTheme1"
                    :maxSecretLevel="process.f_SecretLevel"
                    drag
                    :accept="appConfig.file.accept"
                  ></l-upload>
                </el-form-item>

                <el-form-item class="l-task-btns">
                  <el-button
                    v-for="(btn, index) in taskBtns"
                    :key="index"
                    :type="btn.type"
                    @click="handleBtnClick(btn)"
                    >{{ $t(btn.name) }}</el-button
                  >
                </el-form-item>
              </el-form>
              <l-wf-audit-info :data="userLogs"></l-wf-audit-info>
            </div>
          </l-panel>
        </template>
      </l-layout>
    </l-fullscreen-dialog>

    <template v-else-if="wraperType == 'page'">
      <l-layout class="l-tab-page" :right="400">
        <l-panel :style="{ 'padding-right': isRead ? '' : 0 }">
          <div class="l-auto-window" style="padding: 0 8px">
            <el-tabs v-model="activeName" @tab-click="handleTabClick">
              <el-tab-pane v-if="hasWfForm" :label="$t('表单信息')" name="form">
                <div class="l-rblock" v-loading="formSchemeLoding">
                  <template v-if="showForm">
                    <l-form-viewer
                      v-if="formType == '1'"
                      :formInfo="formInfo"
                      :isWfForm="true"
                      :authFieldsMap="formAuthFieldsMap"
                      ref="wfForm"
                    ></l-form-viewer>
                    <component
                      ref="wfForm"
                      v-else
                      :requiredMap="formRequiredMap"
                      :authFieldsMap="formAuthFieldsMap"
                      :isWfForm="true"
                      :is="sysFormComponent"
                      :isReadOnly="isWfReadOnly"
                    ></component>
                  </template>
                </div>
              </el-tab-pane>
              <el-tab-pane :label="$t('流程信息')" name="wfinfo">
                <l-layout style="background: #f1f2f5" :right="320">
                  <l-panel
                    class="flow-panel"
                    style="padding: 0; padding-top: 0"
                  >
                    <template #title>
                      <el-button-group>
                        <el-tooltip
                          effect="dark"
                          :content="$t('复原')"
                          placement="bottom"
                        >
                          <el-button
                            size="mini"
                            icon="el-icon-aim"
                            @click="resetZoom"
                          ></el-button>
                        </el-tooltip>
                        <el-tooltip
                          effect="dark"
                          :content="$t('放大')"
                          placement="bottom"
                        >
                          <el-button
                            size="mini"
                            icon="el-icon-zoom-in"
                            @click="handlerZoom(0.1)"
                          ></el-button>
                        </el-tooltip>
                        <el-tooltip
                          effect="dark"
                          :content="$t('缩小')"
                          placement="bottom"
                        >
                          <el-button
                            size="mini"
                            icon="el-icon-zoom-out"
                            @click="handlerZoom(-0.1)"
                          ></el-button>
                        </el-tooltip>
                      </el-button-group>

                      <div style="float: right">
                        <el-tag
                          size="small"
                          effect="plain"
                          style="margin-right: 8px"
                          >{{$t('正在审核')}}</el-tag
                        >
                        <el-tag
                          size="small"
                          effect="plain"
                          style="margin-right: 8px"
                          type="success"
                          >{{$t('已审核')}}</el-tag
                        >
                        <el-tag
                          size="small"
                          effect="plain"
                          style="margin-right: 8px"
                          type="danger"
                          >{{$t('已审核（驳回）')}}</el-tag
                        >
                      </div>
                    </template>
                    <b-wflow-viewer
                      ref="bflow"
                      isSimple
                      @elementClick="elementClick"
                    >
                    </b-wflow-viewer>
                  </l-panel>
                  <template #right>
                    <l-panel
                      v-if="nodeLogs.length > 0"
                      class="flow-panel"
                      style="padding: 0; padding-top: 0"
                    >
                      <template #title>{{ $t('记录信息') }}</template>
                      <div
                        class="l-rblock"
                        style="padding: 8px; overflow: hidden auto"
                      >
                        <el-timeline>
                          <el-timeline-item
                            :type="item.type"
                            v-for="(item, index) in nodeLogs"
                            :key="index"
                            :timestamp="item.time"
                            placement="top"
                          >
                            <el-card shadow="hover">
                              <div class="title">{{ item.name }}</div>
                              <div class="content">
                                <template v-if="item.taskType != 3">
                                  <l-user
                                    v-for="(userId, index2) in item.userIds"
                                    :key="index2"
                                    :value="userId"
                                  ></l-user>
                                  {{ item.des }}
                                  <div v-if="item.desEx">{{ item.desEx }}</div>
                                </template>
                                <template v-else>
                                  <el-button
                                    size="mini"
                                    @click="OpenChildWf(item)"
                                    type="text"
                                    >{{ $t("查看") }}</el-button
                                  >
                                  <template v-if="item.isShowUser">
                                    <l-user
                                      v-for="(userId, index2) in item.userIds"
                                      :key="index2"
                                      :value="userId"
                                    ></l-user>
                                  </template>

                                  {{ item.des }}
                                  <div v-if="item.desEx">{{ item.desEx }}</div>
                                </template>
                              </div>
                            </el-card>
                          </el-timeline-item>
                        </el-timeline>
                      </div>
                    </l-panel>
                  </template>
                </l-layout>
              </el-tab-pane>
              <el-tab-pane
                v-if="logs.length > 0"
                :label="$t('流转记录')"
                name="wflogs"
              >
                <div
                  class="l-rblock"
                  style="padding: 8px; overflow: hidden auto"
                >
                  <el-timeline>
                    <el-timeline-item
                      :type="item.type"
                      v-for="(item, index) in logs"
                      :key="index"
                      :timestamp="item.time"
                      placement="top"
                    >
                      <el-card shadow="hover">
                        <div class="title">{{ item.name }}</div>
                        <div class="content">
                          <template v-if="item.taskType != 3">
                            <l-user
                              v-for="(userId, index2) in item.userIds"
                              :key="index2"
                              :value="userId"
                            ></l-user>
                            {{ item.des }}
                            <div v-if="item.desEx">{{ item.desEx }}</div>
                          </template>
                          <template v-else>
                            <el-button
                              size="mini"
                              @click="OpenChildWf(item)"
                              type="text"
                              >{{ $t("查看") }}</el-button
                            >
                            <template v-if="item.isShowUser">
                              <l-user
                                v-for="(userId, index2) in item.userIds"
                                :key="index2"
                                :value="userId"
                              ></l-user>
                            </template>

                            {{ item.des }}
                            <div v-if="item.desEx">{{ item.desEx }}</div>
                          </template>
                        </div>
                      </el-card>
                    </el-timeline-item>
                  </el-timeline>
                </div>
              </el-tab-pane>
            </el-tabs>
          </div>
        </l-panel>

        <template #right v-if="!isRead">
          <l-panel style="padding-left: 0" :title="$t('审批栏')">
            <div class="l-rblock" style="padding: 8px">
              <el-form
                :model="formData"
                :rules="myRules"
                size="mini"
                ref="form"
              >
                <el-form-item
                  v-if="
                    !isCreateSub && (type != 'auditAndlook' || task != null)
                  "
                  :label="isCreateAgain ? $t('备注') : $t('审批意见')"
                  prop="des"
                >
                  <el-input
                    type="textarea"
                    v-model="formData.des"
                    :placeholder="$t('please enter')"
                    rows="3"
                  >
                  </el-input>
                </el-form-item>
                <el-form-item
                  :label="$t('流程标题')"
                  prop="title"
                  v-if="isCreateSub && isCustmerTitle"
                >
                  <el-input v-model="formData.title" :placeholder="$t('please enter')">
                  </el-input>
                </el-form-item>
                <el-form-item
                  prop="fileId"
                  v-if="isUploadFile"
                  style="margin-bottom:0;"
                >
                  <l-upload
                    v-model="formData.fileId"
                    showFileList="uploadTheme1"
                    :maxSecretLevel="process.f_SecretLevel"
                    drag
                    :accept="appConfig.file.accept"
                  ></l-upload>
                </el-form-item>
                <el-form-item class="l-task-btns">
                  <el-button
                    v-for="(btn, index) in taskBtns"
                    :key="index"
                    :type="btn.type"
                    @click="handleBtnClick(btn)"
                    >{{ btn.name }}</el-button
                  >

                  <l-wordprint-btn
                    style="margin-right: 8px"
                    v-if="currentNode.formWrodPrintCode"
                    :code="currentNode.formWrodPrintCode"
                    :getFormData="getPrintData"
                  ></l-wordprint-btn>
                </el-form-item>
              </el-form>
              <l-wf-audit-info :data="userLogs"></l-wf-audit-info>
            </div>
          </l-panel>
        </template>
      </l-layout>
    </template>

    <template v-else-if="wraperType == 'btn'">
      <el-button
        size="mini"
        v-for="(btn, index) in taskBtns"
        :key="index"
        :type="btn.type"
        @click="handleBtnClick(btn)"
        >{{ btn.name }}</el-button
      >
    </template>

    <l-dialog
      :width="500"
      :height="nodeUsers.length * 48 + 88"
      :title="$t('选择下一审核节点人员')"
      :visible.sync="selectUsersVisible"
      @ok="handleSelectUsersSave"
      @close="handleSelectUsersCloseForm"
      :showClose="false"
    >
      <select-users ref="selectUsers" :nodeList="nodeUsers"></select-users>
    </l-dialog>

    <l-dialog
      :title="$t(tUserType == 1 ? `选择转移人员` : `选择加签人员`)"
      :visible.sync="selectTUserVisible"
      :height="480"
      width="1024px"
      :hasBtns="false"
    >
      <l-user-select-panel
        @change="handleChange"
        :multiple="false"
        ref="userSelectPanel"
      ></l-user-select-panel>
    </l-dialog>

    <l-dialog
      :title="$t('驳回节点选择')"
      :visible.sync="selectRejectNodeVisible"
      :height="136"
      :width="500"
      @ok="handleSelectRejectNodeSave"
      @close="handleRejectNodeCloseForm"
      :showClose="false"
    >
      <select-reject-node
        ref="selectRejectNode"
        :nodeList="completedNodes"
      ></select-reject-node>
    </l-dialog>

    <!--选择签章-->
    <l-dialog
      :title="$t('选择签章')"
      :visible.sync="selectSignVisible"
      :height="480"
      :width="508"
      @ok="handleSelectSignSave"
      @closed="handleSelectSignCloseForm"
      @opened="handleSelectSignOpenForm"
    >
      <select-sign ref="SelectSign"></select-sign>
    </l-dialog>

    <look-other-form
      ref="otherForm"
      type="lookmy"
      :params="{ processId: otherProcessId }"
      :isLoadFormData="true"
      :visible.sync="otherVisible"
      :isParent="isOtherParent"
      :childId="processId"
    >
    </look-other-form>
  </div>
</template>

<script>
import mixin from "../../../mixins/wf";
import SelectUsers from "./selectAuditUsers.vue";
import SelectRejectNode from "./selectRejectNode.vue";
import SelectSign from "./selectSign.vue";
import LookOtherForm from "./lookOther.vue";
import wfEvent from "../../../util/event";

const api = window.$api.workflow.process;
const apiStamp = window.$api.workflow.stamp;

export default {
  mixins: [mixin()],
  name: "wf-audit-form",
  components: {
    SelectUsers,
    SelectRejectNode,
    SelectSign,
    LookOtherForm,
  },
  props: {
    isCreateAgain: Boolean,
    isCreateSub: Boolean,
    isRead: Boolean,
    wraperType: {
      type: String,
      default: "full", // full 全屏 ,dialog 弹窗
    },
  },
  data() {
    return {
      midVisible: false,
      formData: {
        des: "",
        fileId: "",
      },
      rules: {
        des: [{ required: true, message: this.$t("请填写审批意见"), trigger: "blur" }],
      },

      currentBtn: null,

      nodeUsers: [],
      selectUsersVisible: false,
      selectTUserVisible: false,
      tUserType: 1, // 1 转移 2 加签,

      selectRejectNodeVisible: false, // 驳回节点选择
      selectSignVisible: false, // 选择签章
      stampList: [],

      otherVisible: false,
      otherProcessId: "",
      isOtherParent: false,

      isCustmerTitle: false,
      isUploadFile: false,

      pageLoading: false,
      pageLoadingText: "",
    };
  },
  computed: {
    myRules() {
      if (this.isCreateAgain || this.isRead) {
        return {};
      } else {
        return this.rules;
      }
    },
    completedNodes() {
      const nodes = this.$deepClone(this.wfData);
      return nodes.filter((t) => t.hasFinish && t.id != this.currentNode.id);
    },
  },
  watch: {
    visible: {
      handler(n) {
        this.midVisible = n;
      },
    },
  },
  async mounted() {
    if (this.wraperType == "btn" || this.wraperType == "page") {
      await this.handleOpened(this.showPgaeLoading, this.hidePageLoading);
    }
  },
  methods: {
    showPgaeLoading(text) {
      this.pageLoadingText = text || this.$t("saving data...");
      this.pageLoading = true;
    },
    hidePageLoading() {
      this.pageLoading = false;
    },

    showWFLoading(text) {
      if (this.$refs.formDialog) {
        this.$refs.formDialog.showLoading(text);
      } else {
        this.showPgaeLoading(text);
      }
    },
    hideWFLoading() {
      if (this.$refs.formDialog) {
        this.$refs.formDialog.hideLoading();
      } else {
        this.hidePageLoading();
      }
    },

    resetZoom() {
      this.$refs.bflow.reset();
    },
    handlerZoom(r) {
      this.$refs.bflow.handlerZoom(r);
    },
    elementClick(node) {
      if (node) {
        this.nodeLogs = this.nodeMap[node.id] || [];
      } else {
        this.nodeLogs = [];
      }
    },

    resetFormToMe() {
      this.$refs.form && this.$refs.form.resetFields();
      this.taskBtns = [];
    },
    setForm() {
      this.isCustmerTitle = false;
      this.isUploadFile = false;

      this.$refs.form && this.$refs.form.clearValidate();
      if (this.task == null) {
        this.currentNode = this.wfData.find((t) => t.type == "startEvent");
        return;
      }

      if (this.task.f_Type == 3) {
        this.currentNode = this.wfData.find((t) => t.type == "startEvent");
        if (this.process == null) {
          this.isCustmerTitle = this.currentNode.isCustmerTitle;
        }
      } else {
        this.currentNode = this.wfData.find((t) => t.id == this.task.f_UnitId);
      }

      this.isUploadFile = this.currentNode.isUploadFile;

      // 设置审核按钮
      const btns = [];
      if (this.currentNode.type == "startEvent") {
        if (this.task.f_Type == 3) {
          btns.push({
            code: "learun_subcreate",
            name: "提交子流程",
            type: "primary",
          });
          btns.push({
            code: "disagree",
            name: "驳回",
            type: "danger",
          });
        } else {
          btns.push({
            code: "learun_create",
            name: "提交",
            type: "primary",
          });
          if (this.currentNode.isDelete) {
            btns.push({
              code: "learun_detete",
              name: "作废",
              type: "danger",
            });
          }
        }
      } else {
        this.currentNode.btnlist.forEach((btn) => {
          if (btn.hidden != true) {
            if (btn.code == "agree") {
              btn.type = "primary";
            } else if (btn.code == "disagree") {
              btn.type = "danger";
            }
            btns.push(btn);
          }
        });

        if (this.currentNode.isAddSign) {
          btns.push({
            code: "learun_sign",
            name: "加签",
            type: "success",
          });
        }

        if (this.currentNode.isTransfer) {
          btns.push({
            code: "learun_transfer",
            name: "转移",
            type: "success",
          });
        }
      }
      this.taskBtns = btns;
    },

    validateForm() {
      if (this.$refs.form) {
        return this.$formValidateWraper(this.$refs.form);
      } else {
        return true;
      }
    },

    handleBtnClick(btn) {
      this.showWFLoading("流程处理中...");
      this.$nextTick(async () => {
        this.currentBtn = btn;

        if (btn.code != "agree" && !(await this.validateForm())) {
          this.hideWFLoading();
          return;
        }

        if(btn.code != "disagree" || this.currentNode.rejectNeedForm){// 流程驳回表单不做校验
          if (!(await this.validateWfForm())) {
            this.hideWFLoading();
            return;
          }
        }
        
        if (!(await this.saveWfForm(btn.code))) {
          this.hideWFLoading();
          return;
        }
       
        let res;
        switch (btn.code) {
          case "learun_create":
            res = await this.$awaitWraper(
              api.createAgain({
                processId: this.processId,
                des: `${this.$t('重新提交')}${this.formData.des ? "-" : ""}${
                  this.formData.des
                }`,
              })
            );
            await wfEvent.createAgain({
              processId: this.processId,
              des: `${this.$t('重新提交')}${this.formData.des ? "-" : ""}${
                this.formData.des
              }`,
            });
            break;
          case "learun_subcreate":
            res = this.createSub();
            break;
          case "learun_detete":
            res = await this.$awaitWraper(api.deleteProcess(this.processId));
            await wfEvent.delete({
              processId: this.processId,
            });
            break;
          case "learun_sign":
            this.tUserType = 2;
            this.selectTUserVisible = true;
            break;
          case "learun_transfer":
            this.tUserType = 1;
            this.selectTUserVisible = true;
            break;
          default:
            if (this.task.f_Type == 6) {
              // 加签审核
              res = await this.$awaitWraper(
                api.signAudit(this.taskId, {
                  code: btn.code,
                  name: btn.name,
                  des: this.formData.des,
                  fileId: this.formData.fileId,
                })
              );

              await wfEvent.signAudit({
                processId: this.processId,
                taskId: this.taskId,
                code: btn.code,
                name: btn.name,
                des: this.formData.des,
                fileId: this.formData.fileId,
              });
            } else if (this.task.f_Type == 3) {
              res = await this.$awaitWraper(
                api.audit(this.taskId, {
                  code: this.currentBtn.code,
                  name: this.currentBtn.name,
                  des: this.formData.des,
                  fileId: this.formData.fileId,
                })
              );

              await wfEvent.audit({
                processId: this.processId,
                taskId: this.taskId,
                code: this.currentBtn.code,
                name: this.currentBtn.name,
                des: this.formData.des,
                fileId: this.formData.fileId,
              });
            } else {
              if (
                this.currentNode.rejectType == "2" &&
                btn.code == "disagree"
              ) {
                this.selectRejectNodeVisible = true;
                this.hideWFLoading();
                return;
              }

              if (btn.isSign) {
                // 加载签章数据
                const stampList = await this.$awaitWraper(
                  apiStamp.getList(this.loginInfo.f_UserId)
                );

                if (stampList && stampList.length > 0) {
                  this.stampList = stampList;
                  this.selectSignVisible = true;
                  this.hideWFLoading();
                  return;
                }
              }

              res = await this.audit();
            }

            break;
        }
        this.hideWFLoading();
        if (res) {
          this.midVisible = false;
          this.$emit("refresh");
        }
      });
    },

    async createSub() {
      // 获取接下来节点审核人
      if (this.currentNode.isNextAuditor) {
        const res = await api.getNextUsers({
          schemeId: this.task.f_ChildSchemeId,
          processId: this.processId,
          nodeId: this.currentNode.id,
        });
        const nodeUserMap = res.data.data;
        const nodeUsers = [];
        for (let key in nodeUserMap) {
          const nodeUserItem = nodeUserMap[key];
          if (nodeUserItem.length > 1) {
            nodeUsers.push({
              name: this.wfData.find((t) => t.id == key).name,
              id: key,
              options: nodeUserItem.map((t) => {
                return { value: t.id, label: t.name };
              }),
            });
          }
        }

        this.nodeUsers = nodeUsers;

        if (this.nodeUsers.length > 0) {
          this.selectUsersVisible = true;
          this.hideWFLoading();
          return;
        }
      }

      // 创建流程
      const wfData = {
        processId: this.processId,
        schemeId: this.task.f_ChildSchemeId,
        title: this.formData.title,
        parentTaskId: this.task.f_Id,
      };

      const res = await this.$awaitWraper(api.createSub(wfData));

      await wfEvent.createSub(wfData);

      return res;
    },

    async audit() {
      // 获取接下来节点审核人
      if (this.currentBtn.isNextAuditor) {
        const res = await api.getNextUsers({
          processId: this.processId,
          nodeId: this.currentNode.id,
        });
        const nodeUserMap = res.data.data;
        const nodeUsers = [];
        for (let key in nodeUserMap) {
          const nodeUserItem = nodeUserMap[key];
          if (nodeUserItem.length > 1) {
            nodeUsers.push({
              name: this.wfData.find((t) => t.id == key).name,
              id: key,
              options: nodeUserItem.map((t) => {
                return { value: t.id, label: t.name };
              }),
            });
          }
        }

        this.nodeUsers = nodeUsers;

        if (this.nodeUsers.length > 0) {
          this.selectUsersVisible = true;
          return;
        }
      }

      const res = await this.$awaitWraper(
        api.audit(this.taskId, {
          code: this.currentBtn.code,
          name: this.currentBtn.name,
          des: this.formData.des,
          fileId: this.formData.fileId,
        })
      );

      await wfEvent.audit({
        processId: this.processId,
        taskId: this.taskId,
        code: this.currentBtn.code,
        name: this.currentBtn.name,
        des: this.formData.des,
        fileId: this.formData.fileId,
      });

      return res;
    },

    handleSelectUsersSave() {
      this.selectUsersVisible = false;
      this.showWFLoading("流程处理中...");
      const nextUsers = this.$refs.selectUsers.getForm();
      this.$nextTick(async () => {
        let res;

        if (this.task.f_Type == 3) {
          // 创建流程
          const wfData = {
            processId: this.processId,
            schemeId: this.task.f_ChildSchemeId,
            title: this.formData.title,
            parentTaskId: this.task.f_Id,
            nextUsers: nextUsers,
          };
          res = await this.$awaitWraper(api.createSub(wfData));
        } else {
          res = await this.$awaitWraper(
            api.audit(this.taskId, {
              code: this.currentBtn.code,
              name: this.currentBtn.name,
              nextUsers: nextUsers,
              des: this.formData.des,
              fileId: this.formData.fileId,
            })
          );
        }

        if (res) {
          await wfEvent.audit({
            processId: this.processId,
            taskId: this.taskId,
            code: this.currentBtn.code,
            name: this.currentBtn.name,
            des: this.formData.des,
            fileId: this.formData.fileId,
            nextUsers: nextUsers,
          });
          this.midVisible = false;
        }
        this.hideWFLoading();
        this.$emit("refresh");
      });
    },
    handleSelectUsersCloseForm() {
      this.$refs.selectUsers.resetForm();
    },
    handleChange(userInfo) {
      if (userInfo) {
        const title = this.tUserType == 1 ? this.$t("转移") : this.$t("加签");
        if (this.loginInfo.f_UserId == userInfo.f_UserId) {
          this.$message({
            type: "warning",
            message: `${title}${this.$t("不能给自己本人")}`,
          });
          return;
        }

        this.$confirm(`${this.$t("是否confirm")}${title}${this.$t("给")}${userInfo.f_RealName}?`, this.$t("Tips"), {
          confirmButtonText: this.$t("confirm"),
          cancelButtonText: this.$t("cancel"),
          type: "warning",
        })
          .then(() => {
            this.selectTUserVisible = false;
            this.showWFLoading("流程处理中...");

            this.$nextTick(async () => {
              let res;

              if (this.tUserType == 1) {
                res = await this.$awaitWraper(
                  api.transferUser(this.taskId, {
                    toUserId: userInfo.f_UserId,
                    des: `${this.$t("转移给")}${userInfo.f_RealName}${
                      this.formData.des ? "-" : ""
                    }${this.formData.des}`,
                    fileId: this.formData.fileId,
                  })
                );

                await wfEvent.transferUser({
                  processId: this.processId,
                  taskId: this.taskId,
                  toUserId: userInfo.f_UserId,
                  des: `${this.$t("转移给")}${userInfo.f_RealName}${
                    this.formData.des ? "-" : ""
                  }${this.formData.des}`,
                  fileId: this.formData.fileId,
                });
              } else {
                res = await this.$awaitWraper(
                  api.sign(this.taskId, {
                    toUserId: userInfo.f_UserId,
                    des: `${this.$t("加签给")}${userInfo.f_RealName}${
                      this.formData.des ? "-" : ""
                    }${this.formData.des}`,
                    fileId: this.formData.fileId,
                  })
                );

                await wfEvent.sign({
                  processId: this.processId,
                  taskId: this.taskId,
                  toUserId: userInfo.f_UserId,
                  des: `${this.$t("加签给")}${userInfo.f_RealName}${
                    this.formData.des ? "-" : ""
                  }${this.formData.des}`,
                  fileId: this.formData.fileId,
                });
              }

              this.hideWFLoading();

              if (res) {
                this.midVisible = false;
                this.$emit("refresh");
              }
            });
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: `${this.$t("已cancel")}${title}`,
            });
          });
      }
    },

    async handleSelectRejectNodeSave() {
      if (await this.$refs.selectRejectNode.validateForm()) {
        this.showWFLoading("流程处理中...");
        const nextId = this.$refs.selectRejectNode.getForm();
        this.selectRejectNodeVisible = false;
        this.$nextTick(async () => {
          const res = await this.$awaitWraper(
            api.audit(this.taskId, {
              code: this.currentBtn.code,
              name: this.currentBtn.name,
              nextId: nextId,
              des: this.formData.des,
              fileId: this.formData.fileId,
            })
          );

          if (res) {
            await wfEvent.audit({
              processId: this.processId,
              taskId: this.taskId,
              code: this.currentBtn.code,
              name: this.currentBtn.name,
              des: this.formData.des,
              fileId: this.formData.fileId,
              nextId: nextId,
            });
            this.midVisible = false;
          }
          this.hideWFLoading();
          this.$emit("refresh");
        });
      }
    },
    handleRejectNodeCloseForm() {
      this.$refs.selectRejectNode.resetForm();
    },

    async handleRead() {
      this.showWFLoading("流程处理中...");
      const res = await this.$awaitWraper(api.readAudit(this.taskId));
      if (res) {
        this.midVisible = false;
      }
      this.hideWFLoading();
      this.$emit("refresh");
    },

    // 签章
    async handleSelectSignSave() {
      if (await this.$refs.SelectSign.validateForm()) {
        this.showWFLoading("流程处理中...");
        const { f_StampId, f_Password } = this.$refs.SelectSign.getForm();
        this.selectSignVisible = false;
        this.$nextTick(async () => {
          const res = await this.$awaitWraper(
            api.audit(this.taskId, {
              code: this.currentBtn.code,
              name: this.currentBtn.name,
              stampImg: f_StampId,
              stampPassWord: f_Password,
              des: this.formData.des,
              fileId: this.formData.fileId,
            })
          );
          if (res) {
            await wfEvent.audit({
              processId: this.processId,
              taskId: this.taskId,
              code: this.currentBtn.code,
              name: this.currentBtn.name,
              des: this.formData.des,
              fileId: this.formData.fileId,
              stampImg: f_StampId,
              stampPassWord: f_Password,
            });
            this.midVisible = false;
          }
          this.hideWFLoading();
          this.$emit("refresh");
        });
      }
    },
    handleSelectSignCloseForm() {
      this.$refs.SelectSign.resetForm();
    },
    handleSelectSignOpenForm() {
      this.$refs.SelectSign.setForm(this.stampList);
    },

    OpenChildWf(row) {
      this.otherProcessId = row.childProcessId;
      this.isOtherParent = false;
      this.otherVisible = true;
    },
    handleOpenParent() {
      this.otherProcessId = this.parentProcessId;
      this.isOtherParent = true;
      this.otherVisible = true;
    },
  },
};
</script>

<style lang="scss">
.l-task-btns {
  .el-button {
    margin: 0;
    margin-top: 8px;
    margin-right: 8px;
  }
}
</style>
